package com.cloudcc.frame.trigger;


import com.cloudcc.deveditor.core.CCObject;
import com.cloudcc.deveditor.core.UserInfo;
import com.cloudcc.deveditor.trigger.TriggerEditor;
import com.cloudcc.frame.Utils.EleGetGuarantee2;
import com.cloudcc.frame.Utils.EleQueryCustomer2;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class eleopp_Test extends TriggerEditor {
    public void beforeInsert(Map record_new, UserInfo userInfo, Map record_old) {

        //测试环境：电子保函客户的记录类型
        String AC_RCTYPE = "20211C59581DC5CZOn5N";
        String socialCreditCode = "";
        String RCODE = "0000";
        //关联客户
        String khmc = record_new.get("khmc") == null ? "" : record_new.get("khmc") + "";
        //记录id
        String id = record_new.get("id") == null ? "" : record_new.get("id") + "";
        /*查询客户信息,*/
        String acc_sql = "select id,recordtype,invoiceTaxNo from Account where id='" + khmc + "' and is_deleted='0'";
        List<CCObject> account = this.cqlQuery("Account", acc_sql);
        if (account.size() > 0) {
            socialCreditCode = account.get(0).get("invoiceTaxNo") == null ? "" : account.get(0).get("invoiceTaxNo") + "";
            String update_acc_sql = "update Account set recordtype='" + AC_RCTYPE + "' where id='" + khmc + "'";
            //客户记录类型更改
            this.cqlQuery("Account", update_acc_sql);

        }
        /*查询会员信息*/
        EleQueryCustomer2 eqc2 = new EleQueryCustomer2(userInfo);
        net.sf.json.JSONObject params = new net.sf.json.JSONObject();
        net.sf.json.JSONObject data = new net.sf.json.JSONObject();
        params.put("invokeId", "");
        data.put("cusCertType", "1");
        data.put("cusCertNo", socialCreditCode);
        params.put("data", data);
        String rs = eqc2.sendPost("", params.toString());
        net.sf.json.JSONObject result = net.sf.json.JSONObject.fromObject(rs);
        String resultCode = result.getString("resultCode");
        if (resultCode.equals(RCODE)) {
            net.sf.json.JSONObject info = result.getJSONObject("data");
            if (!info.isNullObject()) {
                net.sf.json.JSONObject params2 = new net.sf.json.JSONObject();
                net.sf.json.JSONObject data2 = new net.sf.json.JSONObject();
                params2.put("invokeId", "");
                data2.put("cusCertNo", socialCreditCode);
                params2.put("data", data2);
                record_new.put("accountTime", info.get("createTime") == null ? "" : info.get("createTime") + "");
            }
        }
    }

    public void 备份beforeInsert(Map record_new, UserInfo userInfo, Map record_old) {

        //测试环境：电子保函客户的记录类型
        String AC_RCTYPE = "20211C59581DC5CZOn5N";
        String socialCreditCode = "";
        String RCODE = "0000";
        //商机阶段
        String JD1 = "1获取商机";
        String JD2 = "2建立联系";
        String JD3 = "3确认意向";
        String JD4 = "4客户注册";
        String JD5 = "5首次开函";
        String JD6 = "6二次开函";
        //使用保函形式
        String use_type = "未知";
        //超时未开函
        int letter_end_day = 15;
        //超时未注册
        int register_end_day = 7;
        //未注册提醒
        int remind_wzc_day = 5;
        //未开函提醒
        int remind_wkh_day = 9;
        //关联客户
        String khmc = record_new.get("khmc") == null ? "" : record_new.get("khmc") + "";
        String check_sql = "select id from eleopp where khmc='" + khmc + "' " +
                "and is_deleted='0' and jieduan in('" + JD1 + "','" + JD2 + "','" + JD3 + "','" + JD4 + "','" + JD5 + "','" + JD6 + "')";
        List<CCObject> chechlist = this.cqlQuery("", check_sql);
        //if(chechlist.size()>0){
        //if(true)trigger.addErrorMessage("该客户已经创建了商机，不允许再创建商机");
        // }

        //记录id
        String id = record_new.get("id") == null ? "" : record_new.get("id") + "";
        Date date = new Date();
        SimpleDateFormat sf_day = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sf_time.format(date);
        Calendar c = Calendar.getInstance();
        //过去30天
        c.setTime(new Date());
        c.add(Calendar.DATE, -30);
        Date d = c.getTime();
        String start_time = sf_day.format(d);
        String end_time = sf_day.format(date);

        //开始时间
        record_new.put("start_time", start_time);
        //结束时间
        record_new.put("end_time", end_time);
        //阶段
        record_new.put("jieduan", JD1);
        //超时未开函时间
        record_new.put("letter_end_day", letter_end_day);
        //超时未注册
        record_new.put("register_end_day", register_end_day);
        //未注册提醒
        record_new.put("remind_wzc_day", remind_wzc_day);
        //未开函提醒
        record_new.put("remind_wkh_day", remind_wkh_day);
        //使用保函形式
        record_new.put("use_type", use_type);
        /*查询客户信息,有的话更改记录类型并且做关联*/
        String acc_sql = "select id,recordtype,invoiceTaxNo from Account where id='" + khmc + "' and is_deleted='0'";
        List<CCObject> account = this.cqlQuery("Account", acc_sql);
        if (account.size() > 0) {
            socialCreditCode = account.get(0).get("invoiceTaxNo") == null ? "" : account.get(0).get("invoiceTaxNo") + "";
            String update_acc_sql = "update Account set recordtype='" + AC_RCTYPE + "' where id='" + khmc + "'";
            //客户记录类型更改
            this.cqlQuery("Account", update_acc_sql);
        }


        /*查询会员信息*/
        EleQueryCustomer2 eqc2 = new EleQueryCustomer2(userInfo);
        net.sf.json.JSONObject params = new net.sf.json.JSONObject();
        net.sf.json.JSONObject data = new net.sf.json.JSONObject();
        params.put("invokeId", "");
        data.put("cusCertType", "1");
        data.put("cusCertNo", socialCreditCode);
        params.put("data", data);
        String rs = eqc2.sendPost("", params.toString());
        net.sf.json.JSONObject result = net.sf.json.JSONObject.fromObject(rs);
        String resultCode = result.getString("resultCode");
        if (resultCode.equals(RCODE)) {
            net.sf.json.JSONObject info = result.getJSONObject("data");
            if (!info.isNullObject()) {
                record_new.put("jieduan", JD4);
                EleGetGuarantee2 egg2 = new EleGetGuarantee2(userInfo);
                net.sf.json.JSONObject params2 = new net.sf.json.JSONObject();
                net.sf.json.JSONObject data2 = new net.sf.json.JSONObject();
                params2.put("invokeId", "");
                data2.put("cusCertNo", socialCreditCode);
                params2.put("data", data2);
                String dd_rs = egg2.sendPost("", params2.toString());
                net.sf.json.JSONObject dd_result = net.sf.json.JSONObject.fromObject(dd_rs);
                String resultCode2 = dd_result.getString("resultCode");
                String time = record_old.get("accountTime") == null ? "" : record_old.get("accountTime") + "";
                if (time.equals("")) {
                    record_new.put("accountTime", now);
                }
                if (resultCode2.equals(RCODE)) {
                    net.sf.json.JSONArray dd_arr = dd_result.getJSONArray("data");

                    if (dd_arr.size() > 0) {
                        if (dd_arr.size() == 1) {
                            record_new.put("jieduan", JD5);
                            String guaranteeCreateDate = dd_arr.getJSONObject(0).getString("guaranteeCreateDate");
                            //首次开函时间
                            record_new.put("open_time", guaranteeCreateDate);
                        } else {
                            record_new.put("jieduan", JD6);
                            int first = dd_arr.size() - 1;
                            int second = dd_arr.size() - 2;
                            String open_time = dd_arr.getJSONObject(first).getString("guaranteeCreateDate");
                            String second_time = dd_arr.getJSONObject(second).getString("guaranteeCreateDate");
                            record_new.put("open_time", open_time);
                            //二次开函时间
                            record_new.put("second_time", second_time);
                        }
                    }
                }

            }
        }


    }

    /*
     * @Description:丢单申请审批流程走完，执行触发器
     * 1 获取需要的变量
     * 2 判断是否完成审批
     * 3 更新商机状态
     * 4 更新管护权状态
     * 5 通知
     * @T(n):
     * @Author: zxb
     * @Date:
     * @param null:
     * @return: null
     **/
    public void afterupdate() {
        String api_ele = "eleopp";
        String api_manage_group = "manage_group";
        String jieduan5 = "5-丢单";
        String spzt_pass = "审批成功";
        String lost_status = "已失效";
        String start_status = "已生效";
        String jieduan2 = "2-初次拜访";
        String jieduan3 = "3-客情调研";
        String YDD = "已丢单";

        //获取id
        String id = record_new.get("id") == null ? "" : record_new.get("id") + "";
        //阶段
        String jieduan = record_new.get("jieduan") == null ? "" : record_new.get("jieduan") + "";
        //关联客户
        String khmc = record_new.get("khmc") == null ? "" : record_new.get("khmc") + "";
        //审批状态
        String spzt = record_new.get("spzt") == null ? "" : record_new.get("spzt") + "";
        //旧的审批状态
        String spzt_old = record_old.get("spzt") == null ? "" : record_old.get("spzt") + "";
        //交易中心
        String fk_psmc = record_new.get("fk_psmc") == null ? "" : record_new.get("fk_psmc") + "";
        //商机所有人
        String ownerid = record_new.get("ownerid") == null ? "" : record_new.get("ownerid") + "";
        //商机名称
        String name = record_new.get("name") == null ? "" : record_new.get("name") + "";
        //近一年公招项目投标次数
        String one_year_num = record_new.get("one_year_num") == null ? "" : record_new.get("one_year_num") + "";
        //投标习惯
        String habbit = record_new.get("habbit") == null ? "" : record_new.get("habbit") + "";
        //投标策略
        String strategy = record_new.get("strategy") == null ? "" : record_new.get("strategy") + "";
        //保证金缴纳方式
        String pay_method = record_new.get("pay_method") == null ? "" : record_new.get("pay_method") + "";
        //投标决策人
        String decision = record_new.get("decision") == null ? "" : record_new.get("decision") + "";
        //投标经办人
        String tender = record_new.get("tender") == null ? "" : record_new.get("tender") + "";
        Date date = new Date();
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sf2.format(date);
        //丢单之后的逻辑
        if ((!spzt_old.equals(spzt)) && spzt.equals(spzt_pass)) {
            this.cqlQuery(api_ele, "update eleopp set jieduan='" + jieduan5 + "',status1='" + YDD + "',lose_time='" + now + "',sqyy='主动丢单' where id='" + id + "'");
            String manager_sql = "select * from manage_group where fk_ccuser='" + ownerid + "' and fk_account='" + khmc + "'";

            List<CCObject> manage_group = this.cqlQuery("manage_group", manager_sql);
            if (manage_group.size() > 0) {
                for (CCObject cc :
                        manage_group) {
                    cc.put("ghzt", lost_status);
                    this.update(cc);
                }

            }
            CCObject notice = new CCObject("notice");
            notice.put("accountId", khmc);
            notice.put("companyName", name);
            notice.put("noticeInfo", "你的商机为：" + name + "已丢单");
            this.insert(notice);
        }
        //阶段2，升迁三阶段，所有字段填写完毕；更新管护小组状态为第三阶段
        if (jieduan.equals(jieduan2) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(one_year_num) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(habbit) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(strategy) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(pay_method) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(decision) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(tender)) {
            String manager_sql = "update manage_group set ghzt='" + start_status + "'" +
                    "where fk_account='" + khmc + "' " +
                    "and is_deleted='0' " +
                    "and fk_psmc='" + fk_psmc + "'";
            String eleopp3_sql = "update eleopp set jieduan='" + jieduan3 + "' " +
                    "where id='" + id + "'";
            //更新三阶段
            this.cqlQuery(api_ele, eleopp3_sql);
            //更新管护小组状态
            this.cqlQuery(api_manage_group, manager_sql);
            CCObject notice = new CCObject("notice");
            notice.put("accountId", khmc);
            notice.put("companyName", name);
            notice.put("noticeInfo", "你的商机为：" + name + "升迁为第三阶段");
            this.insert(notice);
        }


    }


    public void afterInsert() {

        String accountName = record_new.get("khmc") == null ? "" : record_new.get("khmc") + "";
        String id = record_new.get("id") == null ? "" : record_new.get("id") + "";
        String fk_psmc = record_new.get("fk_psmc") == null ? "" : record_new.get("fk_psmc") + "";
        String ownerid = record_new.get("ownerid") == null ? "" : record_new.get("ownerid") + "";
        String name = "[电子保函商机]：";

        if (!accountName.equals("")) {
            String findAccountName = "select name from Account where id = '" + accountName + "' ";
            List<CCObject> account = this.cqlQuery("Account", findAccountName);
            if (account.size() > 0) {
                name += account.get(0).get("name");
            }
            String find = "select frequece from ele_num where fk_psmc ='" + fk_psmc + "' and fk_account ='" + accountName + "'";
            List<CCObject> ele_num = this.cqlQuery("ele_num", find);

            if (ele_num.size() > 0) {
                String frequece = ele_num.get(0).get("frequece") == null ? "" : ele_num.get(0).get("frequece") + "";
                String updateFrequeceSql = "update eleopp set frequence ='" + frequece + "' where id ='" + id + "' ";
                this.cqlQuery("eleopp", updateFrequeceSql);
            }
        }
        String sql = "update eleopp set name = '" + name + "' where id = '" + id + "' ";
        this.cqlQuery("eleopp", sql);


        //测试环境：电子保函客户的记录类型
        String AC_RCTYPE = "20211C59581DC5CZOn5N";
        String socialCreditCode = "";
        String RCODE = "0000";
        //关联客户
        String khmc = record_new.get("khmc") == null ? "" : record_new.get("khmc") + "";
        /*查询客户信息,有的话更改记录类型并且做关联*/
        String acc_sql = "select id,recordtype,invoiceTaxNo from Account where id='" + khmc + "' and is_deleted='0'";
        List<CCObject> account = this.cqlQuery("Account", acc_sql);
        if (account.size() > 0) {
            socialCreditCode = account.get(0).get("invoiceTaxNo") == null ? "" : account.get(0).get("invoiceTaxNo") + "";
            String update_acc_sql = "update Account set recordtype='" + AC_RCTYPE + "' where id='" + khmc + "'";
            //客户记录类型更改
            this.cqlQuery("Account", update_acc_sql);

        }
        /*查询会员信息*/
        EleQueryCustomer2 eqc2 = new EleQueryCustomer2(userInfo);
        net.sf.json.JSONObject params = new net.sf.json.JSONObject();
        net.sf.json.JSONObject data = new net.sf.json.JSONObject();
        params.put("invokeId", "");
        data.put("cusCertType", "1");
        data.put("cusCertNo", socialCreditCode);
        params.put("data", data);
        String rs = eqc2.sendPost("", params.toString());
        CCObject interface_record = new CCObject("interface_record");
        interface_record.put("datas", params);
        interface_record.put("url", "EleQueryCustomer");
        interface_record.put("requestDataLong", rs);
        this.insert(interface_record);
        net.sf.json.JSONObject result = net.sf.json.JSONObject.fromObject(rs);
        String resultCode = result.getString("resultCode");
        if (resultCode.equals(RCODE)) {
            net.sf.json.JSONObject info = result.getJSONObject("data");
            if (!info.isNullObject()) {
                String cusSource = info.get("cusSource") == null ? "" : info.get("cusSource") + "";
                String createTime = info.get("createTime") == null ? "" : info.get("createTime") + "";
                String source = "";
                if (cusSource.equals("HHEG")) {
                    source = "电子保函";
                } else if (cusSource.equals("HHPG0101")) {
                    source = "湖南电子卖场";
                } else if (cusSource.equals("HHOG")) {
                    source = "线下保函";
                }
                String updateSql ="update eleopp set accountTime='"+createTime+"',source='"+source+"' where id ='"+id+"' ";
                this.cqlQuery("eleopp",updateSql);
            }
        }

    }

}




